/**
 * Created by 01 on 2016/3/5.
 */
/**
 * Created by 01 on 2016/3/5.
 */

import java.io.File;


import org.cocos2dx.lib.Cocos2dxActivity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.ClipboardManager;
import android.util.Log;


public class CCJNIHelper {

    private static int INSTALLED = 0; // 表示已经安装，且跟现在这个apk文件是一个版本
    private static int UNINSTALLED = 1; // 表示未安装
    private static int INSTALLED_UPDATE =2; // 表示已经安装，版本比现在这个版本要低，可以点击按钮更新

    private static Context context;





    // ===========================================================
    // Constants
    // ===========================================================

    // ===========================================================
    // Fields
    // ===========================================================
    private static Context sContext = null;
    private static String sPackageName = null;
    private static String sChannelID = null;
    private static CCJNIFuncListener sCCJNIHelperListener = null;
    private static String UserName = null;
    private static String Password = null;
    private static String m_strUserLoginInfo = null;
    private static int m_iEnterMode = 0;
    private static ClipboardManager m_Clipboard;
    // ===========================================================
    // Constructors
    // ===========================================================

    public static void init(final Cocos2dxActivity pContext,
                            final CCJNIFuncListener pCCJNIHelperListener) {
        final ApplicationInfo applicationInfo = pContext.getApplicationInfo();
        CCJNIHelper.sContext = pContext;
        CCJNIHelper.sCCJNIHelperListener = pCCJNIHelperListener;
        CCJNIHelper.sPackageName = applicationInfo.packageName;

        // 获取一个剪贴板服务的句柄
        m_Clipboard =(ClipboardManager)CCJNIHelper.sContext.getSystemService(Context.CLIPBOARD_SERVICE);

        Intent intent = pContext.getIntent();
        Bundle bundel = intent.getExtras();
        if (bundel != null)
        {
            String UserName = bundel.getString("UserName");
            String password = bundel.getString("password");
            String packageName = bundel.getString("packageName");
            m_iEnterMode = bundel.getInt("iEnterMode");

            m_strUserLoginInfo = UserName + ";" + password + ";" + packageName + ";" + m_iEnterMode;
        }

        try {
            ApplicationInfo ai = pContext.getPackageManager().getApplicationInfo(
                    pContext.getPackageName(), PackageManager.GET_META_DATA);
            sChannelID = ai.metaData.getString("TDGA_CHANNEL_ID");
        } catch (Exception e) {
            Log.e("error", "WTF!");
        }
    }

    // 获取Channel ID
    public static String getChannelID() {
        return sChannelID;
    }

    // 读取文件(SD卡优先，否则从apk默认安装目录读取)
    // Cool.Cat
    public static String getReadWritePath() {

        // 优先往SD上写，如果不存在，则写默认手机存储环境
        if (Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            File fp = Environment.getExternalStorageDirectory();
            fp = new File(fp.toString() + "/." + CCJNIHelper.sPackageName);
            fp.mkdirs();
            fp.setWritable(true);
            return fp.toString();
        }
        return "/data/data/" + CCJNIHelper.sPackageName;
    }

    // 包名
    public static String getPackageName() {
        return CCJNIHelper.sPackageName;
    }

    // 干掉
    public static void killProcess() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    // 是否框
    private static void showMsgBoxYesOrNo(final String[] array) {
        CCJNIHelper.sCCJNIHelperListener.showMsgBoxYesOrNo(array);
    }

    private static void showMsgBoxYesOrNo(final String pTitle,
                                          final String pMessage) {
        CCJNIHelper.sCCJNIHelperListener.showMsgBoxYesOrNo(pTitle, pMessage);
    }

    // 下载
    // Cool.Cat
    public static void runDownload(final String Url) {
        CCJNIHelper.sCCJNIHelperListener.runDownload(Url);
    }

    // 安装
    // Cool.Cat
    public static void runSetup(final String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + path);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        CCJNIHelper.sContext.startActivity(intent);
    }

    // 获取用戶登陸信息
    public static String getUserLoginInfo() {
        return m_strUserLoginInfo;
    }

    public static void setUserInfo(final String userName, final String password, final int iEnterMode)
    {
        UserName = userName;
        Password = password;
        m_iEnterMode = iEnterMode;
    }

    public static void startGameApp(final String packageName)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);

        int last = packageName.lastIndexOf(".");
        String strActivity = packageName + packageName.substring(last);
        intent.setComponent(new ComponentName(packageName, strActivity));

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("UserName",UserName);
        intent.putExtra("password",Password);
        intent.putExtra("packageName", CCJNIHelper.sContext.getPackageName());
        intent.putExtra("iEnterMode", m_iEnterMode);

        CCJNIHelper.sContext.startActivity(intent);
    }

    public static void startGameHall(final String packageName)
    {
        Intent LaunchIntent = CCJNIHelper.sContext.getPackageManager().getLaunchIntentForPackage(packageName);
        LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        CCJNIHelper.sContext.startActivity(LaunchIntent);
    }

    public static String isApkInstalled(final String packageName, final String versionInfo)
    {
        Log.i("TAG_isApkInstalled","packageName = "+ packageName + "++++versionInfo = " + versionInfo);

        try {
            PackageManager pakage_Manager = CCJNIHelper.sContext.getPackageManager();
            // 获取PackageManager对象   ,PackageManager.GET_UNINSTALLED_PACKAGES
            ApplicationInfo applicatonInfo = pakage_Manager.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            if (applicatonInfo == null)
            {
                return UNINSTALLED+"";
            }

            PackageInfo info = CCJNIHelper.sContext.getPackageManager().getPackageInfo(packageName, 0);
            // 当前应用的版本名称
            String versionName = info.versionName;
            versionName = versionName.replace(".", "");
            Log.i("TAG_isApkInstalled", "当前应用的版本名称  = " + versionName);
            // 当前版本的版本号
            int versionCode = info.versionCode;
            Log.i("TAG_isApkInstalled", "当前版本的版本号    = " + versionCode);
            // 当前版本的包名
            String packageNames = info.packageName;
            Log.i("TAG_isApkInstalled", "当前版本的包名   = " + packageNames);

            if (!versionName.equals(versionInfo))
                return INSTALLED_UPDATE + "";

            return INSTALLED + "";
            //return UNINSTALLED+"";

        } catch (NameNotFoundException e) {

            String strError = e.getMessage();
            e.printStackTrace();
            //runDownload(DownLoadURL);
            return UNINSTALLED+"";
        }
    }

    //复制到剪贴板
    public static void setAndroidClip(final String strUrl)
    {
        Log.v("setAndroidClip", strUrl);

        m_Clipboard.setText(strUrl); // 复制
    }

    //獲取到剪贴板
    public static String getAndroidClip()
    {
        String StrClip = m_Clipboard.getText().toString(); //粘贴

        return StrClip;
    }

    private boolean isRunningForeground (Context context)
    {
        ActivityManager am = (ActivityManager)context.getSystemService(CCJNIHelper.sContext.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if(currentPackageName.equals(getPackageName()))
        {
            return true ;
        }

        return false ;
    }

    // ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================
    public static interface CCJNIFuncListener {
        public void showMsgBoxYesOrNo(final String[] pArray);

        public void showMsgBoxYesOrNo(final String pTitle, final String pMessage);

        public void runDownload(final String Url);

    }
}

